// @/src/stores/address.js
import { defineStore } from 'pinia';
import { ref } from 'vue';
import { useUserStore } from './user'; // 引入user store，用于获取用户ID
import {
    getAddressesByUserIdAPI,
    addAddressAPI,
    updateAddressAPI,
    deleteAddressAPI,
    getAddressByIdAPI,
    setDefaultAddressAPI
} from '@/api/AddressApi';

export const useAddressStore = defineStore('address', () => {
    // 地址相关的响应式状态
    const addresses = ref([]); // 存储用户地址列表
    const currentAddress = ref(null); // 当前选中的地址
    const defaultAddress = ref(null); // 默认地址

    // 访问用户store以获取当前用户ID
    const userStore = useUserStore();

    /**
     * 辅助函数：获取当前用户ID
     * @returns {Long|null} 当前用户ID，如果未登录则返回null
     */
    const getCurrentUserId = () => {
        return userStore.userInfo?.userId || null;
    };

    /**
     * 获取本地存储的地址数据键名
     * @returns {string} 本地存储键名
     */
    const getAddressStorageKey = () => {
        const userId = getCurrentUserId();
        return userId ? `addresses_${userId}` : 'addresses_guest';
    };

    /**
     * 保存地址数据到本地存储
     */
    const saveAddressesToLocalStorage = () => {
        try {
            const storageKey = getAddressStorageKey();
            const addressData = {
                addresses: addresses.value,
                defaultAddress: defaultAddress.value,
                timestamp: Date.now()
            };
            localStorage.setItem(storageKey, JSON.stringify(addressData));
        } catch (error) {
            console.error('保存地址到本地存储失败:', error);
        }
    };

    /**
     * 从本地存储加载地址数据
     */
    const loadAddressesFromLocalStorage = () => {
        try {
            const storageKey = getAddressStorageKey();
            const storedData = localStorage.getItem(storageKey);

            if (storedData) {
                const addressData = JSON.parse(storedData);
                // 检查数据是否过期（7天，地址数据相对稳定）
                const isExpired = Date.now() - addressData.timestamp > 7 * 24 * 60 * 60 * 1000;

                if (!isExpired) {
                    addresses.value = addressData.addresses || [];
                    defaultAddress.value = addressData.defaultAddress || null;
                    return true;
                } else {
                    // 数据过期，清除本地存储
                    localStorage.removeItem(storageKey);
                }
            }
        } catch (error) {
            console.error('从本地存储加载地址数据失败:', error);
        }
        return false;
    };

    /**
     * 清除本地存储的地址数据
     */
    const clearLocalAddressStorage = () => {
        try {
            const storageKey = getAddressStorageKey();
            localStorage.removeItem(storageKey);
        } catch (error) {
            console.error('清除本地地址存储失败:', error);
        }
    };

    /**
     * 获取用户的所有地址
     * 优先从本地存储加载，如果本地没有数据或数据过期，则从服务器获取
     */
    const fetchAddresses = async (forceRefresh = false) => {
        const userId = getCurrentUserId();
        if (!userId) {
            addresses.value = [];
            defaultAddress.value = null;
            return;
        }

        // 如果不是强制刷新，先尝试从本地存储加载
        if (!forceRefresh && loadAddressesFromLocalStorage()) {
            console.log('从本地存储加载地址数据');
            return;
        }

        try {
            const res = await getAddressesByUserIdAPI(userId);
            if (res.data.code === 1) {
                addresses.value = res.data.data || [];
                // 查找默认地址
                defaultAddress.value = addresses.value.find(addr => addr.isDefault) || null;
                // 保存到本地存储
                saveAddressesToLocalStorage();
            } else {
                throw new Error(res.data.msg || '获取地址列表失败。');
            }
        } catch (error) {
            console.error('Address store fetchAddresses error:', error);
            const errorMessage = error.response?.data?.msg || error.message || '获取地址列表失败，请稍后再试。';
            addresses.value = [];
            defaultAddress.value = null;
            throw new Error(errorMessage);
        }
    };

    /**
     * 添加新地址
     * @param {Object} addressDTO - 地址信息
     * @returns {Promise<Object>} 添加成功后的地址对象
     */
    const addAddress = async (addressDTO) => {
        try {
            const res = await addAddressAPI(addressDTO);
            if (res.data.code === 1) {
                // 添加成功后，重新获取地址列表以保持数据同步
                await fetchAddresses(true); // 强制刷新
                return res.data.data;
            } else {
                throw new Error(res.data.msg || '添加地址失败。');
            }
        } catch (error) {
            console.error('Address store addAddress error:', error);
            const errorMessage = error.response?.data?.msg || error.message || '添加地址失败，请稍后再试。';
            throw new Error(errorMessage);
        }
    };

    /**
     * 更新地址信息
     * @param {number} addressId - 地址ID
     * @param {Object} addressDTO - 地址信息
     * @returns {Promise<Object>} 更新成功后的地址对象
     */
    const updateAddress = async (addressId, addressDTO) => {
        try {
            const res = await updateAddressAPI(addressId, addressDTO);
            if (res.data.code === 1) {
                // 更新成功后，重新获取地址列表以保持数据同步
                await fetchAddresses(true); // 强制刷新
                return res.data.data;
            } else {
                throw new Error(res.data.msg || '更新地址失败。');
            }
        } catch (error) {
            console.error('Address store updateAddress error:', error);
            const errorMessage = error.response?.data?.msg || error.message || '更新地址失败，请稍后再试。';
            throw new Error(errorMessage);
        }
    };

    /**
     * 删除地址
     * @param {number} addressId - 地址ID
     * @returns {Promise<boolean>} 成功返回true
     */
    const deleteAddress = async (addressId) => {
        try {
            const res = await deleteAddressAPI(addressId);
            if (res.data.code === 1) {
                // 从本地状态中移除已删除的地址
                addresses.value = addresses.value.filter(addr => addr.addressId !== addressId);
                // 如果删除的是默认地址，清空默认地址
                if (defaultAddress.value && defaultAddress.value.addressId === addressId) {
                    defaultAddress.value = null;
                }
                // 更新本地存储
                saveAddressesToLocalStorage();
                return true;
            } else {
                throw new Error(res.data.msg || '删除地址失败。');
            }
        } catch (error) {
            console.error('Address store deleteAddress error:', error);
            const errorMessage = error.response?.data?.msg || error.message || '删除地址失败，请稍后再试。';
            throw new Error(errorMessage);
        }
    };

    /**
     * 获取地址详情
     * @param {number} addressId - 地址ID
     * @returns {Promise<Object>} 地址详情对象
     */
    const getAddressById = async (addressId) => {
        try {
            const res = await getAddressByIdAPI(addressId);
            if (res.data.code === 1) {
                currentAddress.value = res.data.data;
                return res.data.data;
            } else {
                throw new Error(res.data.msg || '获取地址详情失败。');
            }
        } catch (error) {
            console.error('Address store getAddressById error:', error);
            const errorMessage = error.response?.data?.msg || error.message || '获取地址详情失败，请稍后再试。';
            throw new Error(errorMessage);
        }
    };

    /**
     * 设置默认地址
     * @param {number} addressId - 地址ID
     * @returns {Promise<boolean>} 成功返回true
     */
    const setDefaultAddress = async (addressId) => {
        const userId = getCurrentUserId();
        if (!userId) {
            throw new Error('用户未登录，请先登录。');
        }
        try {
            const res = await setDefaultAddressAPI(addressId, userId);
            if (res.data.code === 1) {
                // 更新本地状态：将所有地址的isDefault设为false，然后将选中的设为true
                addresses.value.forEach(addr => {
                    addr.isDefault = addr.addressId === addressId;
                });
                // 更新默认地址
                defaultAddress.value = addresses.value.find(addr => addr.addressId === addressId) || null;
                // 更新本地存储
                saveAddressesToLocalStorage();
                return true;
            } else {
                throw new Error(res.data.msg || '设置默认地址失败。');
            }
        } catch (error) {
            console.error('Address store setDefaultAddress error:', error);
            const errorMessage = error.response?.data?.msg || error.message || '设置默认地址失败，请稍后再试。';
            throw new Error(errorMessage);
        }
    };

    /**
     * 清空当前地址信息
     */
    const clearCurrentAddress = () => {
        currentAddress.value = null;
    };

    /**
     * 初始化地址数据
     * 在应用启动时调用，优先从本地存储加载
     */
    const initializeAddresses = async () => {
        const userId = getCurrentUserId();
        if (!userId) {
            addresses.value = [];
            defaultAddress.value = null;
            return;
        }

        // 先尝试从本地存储加载
        if (loadAddressesFromLocalStorage()) {
            console.log('从本地存储初始化地址数据');
        } else {
            // 本地没有数据，从服务器获取
            await fetchAddresses(true);
        }
    };

    // 返回地址状态和方法，供组件使用
    return {
        addresses,
        currentAddress,
        defaultAddress,
        fetchAddresses,
        addAddress,
        updateAddress,
        deleteAddress,
        getAddressById,
        setDefaultAddress,
        clearCurrentAddress,
        initializeAddresses,
        saveAddressesToLocalStorage,
        loadAddressesFromLocalStorage,
        clearLocalAddressStorage
    };
});